/**
 * Created with IntelliJ IDEA.
 * User: osereda
 * Date: 03.06.13
 */
package com.google.code.bankagregator.adapter.bank.sberrus.reader.deposit;

import com.google.code.bankagregator.adapter.exception.AdapterException;
import com.google.code.bankagregator.common.SiteConnect;
import com.google.code.bankagregator.entities.Currency;
import com.google.code.bankagregator.entities.Deposit;
import com.google.code.bankagregator.entities.DepositType;
import com.google.code.bankagregator.entities.State;
import org.jsoup.nodes.Document;

import java.util.ArrayList;
import java.util.List;

public class DepositSberNakopitelni extends AbstractDepositSber {

    private final String PRODUCT_TITLE = "Депозит Накопительный";
    private final String AMOUNT_DIVIDER = "—";

    public DepositSberNakopitelni(String url) {
        super(url);
    }

    /**
     * Get product data for Nakopitelnij deposit.
     *
     * @return
     * @throws AdapterException
     */
    @Override
    public List<Deposit> getDeposits() throws AdapterException {
        List<Deposit> deposits = new ArrayList<>();

        Document page = new SiteConnect(this.getDepositPageURL()).getPage();

        String minSumLine = page.select(MIN_AMOUNT_HTML).first().text();
        String[][] table = getTableHorizontal(page.select(PRODUCT_TABLE_HTML));
        String[] minAmount = getAmount(minSumLine, AMOUNT_DIVIDER);

        for (int x = 1; x < table.length; x++) {
            String curr = table[x][0];
            int minDeposit = getValueByCurrency(minAmount, curr);
            int maxDeposit = -1;

            for (int y = 1; y < table[x].length; y++) {
                String rateValue = table[x][y].replaceAll("[^0-9.,]+", "");
                rateValue = rateValue.replaceAll(",", ".");
                if (rateValue.length() > 0) {

                    int term = Integer.valueOf(table[0][y].replaceAll("\\D+", ""));

                    Deposit deposit = new Deposit();
                    deposit.setRefill(true);
                    deposit.setType(DepositType.Deposit);
                    deposit.setBank(this.getBank());
                    deposit.setName(PRODUCT_TITLE);
                    deposit.setCurrency(Currency.valueOf(curr));
                    deposit.setMaxAmount(maxDeposit);
                    deposit.setMinAmount(minDeposit);
                    deposit.setDepositRate(Double.valueOf(rateValue));
                    deposit.setTerm(DAYS_PER_MONTH * term);
                    deposit.setUrl(this.getDepositPageURL());
                    deposit.setState(State.ACTIVE);
                    deposits.add(deposit);
                }
            }
        }

        return deposits;
    }

}
